package database

import (
	log2 "chess/log"
	"chess/tools"
	"context"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"strconv"
)

func JoinGame(ctx context.Context, userId int, roomId int, isPve bool) error {
	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       1,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	result, err := rdb.SCard(ctx, strconv.Itoa(roomId)).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	if result >= 2 {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Debug", "The room is full")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("the room is full")
	}
	result2, err := rdb.SIsMember(ctx, strconv.Itoa(roomId), userId).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	if result2 == true {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Debug", "Do not join a room again")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("do not join a room again")
	}
	_, err = rdb.SAdd(ctx, strconv.Itoa(roomId), userId).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	if isPve {
		_, err = rdb.SAdd(ctx, strconv.Itoa(roomId), "AlphaGo").Result()
		if err != nil {
			writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "JoinGame", strconv.Itoa(userId), "Warring", err.Error())
			if writeLog == 200 {
				fmt.Println("成功写入日志")
			}
			if err2 != nil {
				fmt.Println("写入日志失败")
			}
			return err
		}
	}
	return err
}
